//
//  InsuranceDataEntryViewController.m
//  PhotoAnnotate
//
//  Created by Bassem El-Tamimi on 19.01.11.
//  Copyright 2011 ePapyrus GmbH. All rights reserved.
//

#import "InsuranceDataEntryViewController.h"
#import "InsuranceViewController.h"
#import "Insurance.h"
#import "InsuranceTabbarController.h"

#import "InsuranceDeviceDetailsViewController.h"
#import "InsuranceAddressViewController.h"
#import "InsuranceBankViewController.h"
#import "BirthdayViewController.h"

#define FEATURES_TAB 1
#define INSURE_TAB 2
#define STATUS_TAB 3

#define DEVICE_SECTION 0
//#define INVOICE_SECTION 1
#define ADDRESS_SECTION 1
#define BIRTH_DATE_SECTION 2
#define BANK_SECTION 3
#define ROBBERY_SECTION 4
#define COST_SECTION 5
#define INFO_SECTION 6
#define ACCEPT_CONDITIONS_SECTION 7


@implementation InsuranceDataEntryViewController

@synthesize tableArray;
@synthesize insuranceViewController;

@synthesize segmentedControl;


#pragma mark -
#pragma mark View lifecycle



- (void)viewDidLoad {
    [super viewDidLoad];
//	[[UIApplication sharedApplication] setStatusBarHidden:NO];
	[self setWantsFullScreenLayout:NO];
	[self generateTableData];
	
}


- (void)viewWillAppear:(BOOL)animated
{
	[self setWantsFullScreenLayout:NO];
	self.navigationController.navigationBar.barStyle = UIBarStyleBlack;
	[self generateTableData];
	[self.tableView reloadData];
	[[NSNotificationCenter defaultCenter] addObserver:self
											 selector:@selector(dateChanged:) 
												 name:@"PurchaseDateChanged" 
											   object:[(InsuranceTabbarController *)[self tabBarController] insuranceData]];
	
	[[NSNotificationCenter defaultCenter] addObserver:self
											 selector:@selector(dateChanged:) 
												 name:@"BirthDateChanged" 
											   object:[(InsuranceTabbarController *)[self tabBarController] insuranceData]];
}

- (void)viewDidAppear:(BOOL)animated 
{
	[self.navigationController setNavigationBarHidden:YES animated:NO];
}



- (void)viewWillDisappear:(BOOL)animated
{
	[[NSNotificationCenter defaultCenter] removeObserver:self name:@"PurchaseDateChanged" object:[(InsuranceTabbarController *)[self tabBarController] insuranceData]];
	[[NSNotificationCenter defaultCenter] removeObserver:self name:@"BirthDateChanged" object:[(InsuranceTabbarController *)[self tabBarController] insuranceData]];

}

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations.
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

#pragma mark -
#pragma mark AlertView delegate method


- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
	
}

#pragma mark -
#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.

	return [self.tableArray count];
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    return 1;
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	
	Insurance *insuranceData = [(InsuranceTabbarController *)[self tabBarController] insuranceData];
	
    static NSString *CellIdentifier = @"Cell";
	static NSString *CellWithDetailIdentifier = @"CellWithDetail";
	static NSString *CellWithSwitchIdentifier = @"CellWithSwitch";
	static NSString *CellWithSegmentsIdentifier = @"CellWithSegments";

    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
	UITableViewCell *cellWithDetail = [tableView dequeueReusableCellWithIdentifier:CellWithDetailIdentifier];
    UITableViewCell *cellWithSwitch = [tableView dequeueReusableCellWithIdentifier:CellWithSwitchIdentifier];
    UITableViewCell *cellWithSegments = [tableView dequeueReusableCellWithIdentifier:CellWithSegmentsIdentifier];

	if (indexPath.section == COST_SECTION || indexPath.section == INFO_SECTION) {
		
		if (cell == nil) {
			cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
			cell.selectionStyle = UITableViewCellSelectionStyleNone;
			cell.textLabel.font = [UIFont boldSystemFontOfSize:17.0];
			[cell.textLabel setLineBreakMode:UILineBreakModeWordWrap];
			[cell.textLabel setNumberOfLines:0];
		}
		
		cell.textLabel.text = [tableArray objectAtIndex:indexPath.section];
		
		return cell;
	}
	
	if (indexPath.section == ACCEPT_CONDITIONS_SECTION) {
		if (cellWithSegments == nil) {
			cellWithSegments = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellWithSegmentsIdentifier] autorelease];
			[cellWithSegments.textLabel setLineBreakMode:UILineBreakModeWordWrap];
			[cellWithSegments.textLabel setNumberOfLines:0];
			cellWithSegments.selectionStyle = UITableViewCellSelectionStyleNone;
			
			cellWithSegments.textLabel.font = [UIFont boldSystemFontOfSize:17.0];
			
		}
		
		NSArray *segments = [NSArray arrayWithObjects:NSLocalizedString(@"INSURANCE_ACCEPT_CONDITIONS_YES_LABEL", @"YES"),
							 NSLocalizedString(@"INSURANCE_ACCEPT_CONDITIONS_NO_LABEL", @"NO"), nil];
		self.segmentedControl = [[UISegmentedControl alloc] initWithItems:segments];
		self.segmentedControl.frame = CGRectMake(-1.0f, -1.0f, 302.0f, 46.0f);
		[self.segmentedControl setSelectedSegmentIndex:insuranceData.insured?0:1];
		
		[self.segmentedControl setEnabled:![insuranceData insured] forSegmentAtIndex:0];
		[self.segmentedControl setEnabled:![insuranceData insured] forSegmentAtIndex:1];
		
		[cellWithSegments.contentView addSubview:segmentedControl];
		
		return cellWithSegments;
	}
	
	if (indexPath.section == DEVICE_SECTION || indexPath.section == ADDRESS_SECTION || indexPath.section == BANK_SECTION || indexPath.section == BIRTH_DATE_SECTION) {
		if (cellWithDetail == nil) {
			cellWithDetail = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellWithDetailIdentifier] autorelease];
			cellWithDetail.textLabel.font = [UIFont boldSystemFontOfSize:17.0];
			
			if ([insuranceData insured]) {
				cell.selectionStyle = UITableViewCellSelectionStyleNone;
			} else {
				cellWithDetail.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
			}


			[cellWithDetail.textLabel setLineBreakMode:UILineBreakModeWordWrap];
			[cellWithDetail.textLabel setNumberOfLines:0];
		}
		
		cellWithDetail.textLabel.text = [tableArray objectAtIndex:indexPath.section];

		return cellWithDetail;
	}
	
	if (indexPath.section == ROBBERY_SECTION) {
		if (cellWithSwitch == nil) {
			cellWithSwitch = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellWithSwitchIdentifier] autorelease];
			cellWithSwitch.textLabel.font = [UIFont boldSystemFontOfSize:17.0];			

		}
		
		cellWithSwitch.textLabel.text = [tableArray objectAtIndex:indexPath.section];
		cellWithSwitch.selectionStyle = UITableViewCellSelectionStyleNone;

		[self.switchCtl setEnabled:![insuranceData insured]];
		UIControl *control = self.switchCtl;
		[cellWithSwitch.contentView addSubview:control];
		
		return cellWithSwitch;
	}
    
    // Configure the cell...
    
//	cell.textLabel.text = [tableArray objectAtIndex:indexPath.section];

    return cell;
}



- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
	UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
	if (indexPath.section == DEVICE_SECTION || indexPath.section == ADDRESS_SECTION || indexPath.section == BANK_SECTION || indexPath.section == INFO_SECTION) {
		UIFont *textFont = [cell.textLabel font];
				
//		UIFont *textFont = [UIFont systemFontOfSize:17.0];
		CGSize textSize = CGSizeMake(tableView.contentSize.width, 999.0);

//		CGSize sizeNeededForText = [(NSString *)[tableArray objectAtIndex:indexPath.section] sizeWithFont:textFont
//																						constrainedToSize:tableView.contentSize
//																							lineBreakMode:UILineBreakModeWordWrap];
		
		CGSize sizeNeededForText = [(NSString *)[tableArray objectAtIndex:indexPath.section] sizeWithFont:textFont 
																						constrainedToSize:textSize 
																							lineBreakMode:UILineBreakModeWordWrap];
		return (CGFloat)sizeNeededForText.height + 30;
	}
	
	return 44.0;
}


- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    NSString *title = nil;
    // Return a title or nil as appropriate for the section.
    switch (section) {
        case DEVICE_SECTION:
            title = NSLocalizedString(@"INSURANCE_DEVICE_SECTION_HEADER", @"Your Device Data");
            break;
//        case INVOICE_SECTION:
//            title = NSLocalizedString(@"INSURANCE_INVOICE_SECTION_HEADER", @"Device Receipt");
//            break;
		case ADDRESS_SECTION:
            title = NSLocalizedString(@"INSURANCE_ADDRESS_SECTION_HEADER", @"Your Address");
            break;
		case BIRTH_DATE_SECTION:
            title = NSLocalizedString(@"INSURANCE_BIRTH_DATE_SECTION_HEADER", @"Your Birthday");
            break;
		case BANK_SECTION:
            title = NSLocalizedString(@"INSURANCE_BANK_SECTION_HEADER", @"Your Bank Information");
            break;
		case ROBBERY_SECTION:
            title = NSLocalizedString(@"INSURANCE_ROBBERY_SECTION_HEADER", @"Optional Insurance");
            break;
		case COST_SECTION:
            title = NSLocalizedString(@"INSURANCE_MONTHLY_SECTION_HEADER", @"Insurance Fee");
            break;
		case INFO_SECTION:
            title = NSLocalizedString(@"INSURANCE_INFO_SECTION_HEADER", @"Important Information");
            break;
		case ACCEPT_CONDITIONS_SECTION:
            title = NSLocalizedString(@"INSURANCE_ACCEPT_CONDITIONS_SECTION_HEADER", @"Read and Accept Conditions");
            break;
        default:
            break;
    }
    return title;
}


- (NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section
{
	NSString *title = nil;
    // Return a title or nil as appropriate for the section.
    switch (section) {
        case DEVICE_SECTION:
            title = NSLocalizedString(@"INSURANCE_DEVICE_SECTION_FOOTER", @"Setting month and year suffices, should you not know the exact purchase date.");
            break;
//        case INVOICE_SECTION:
//            title = NSLocalizedString(@"INSURANCE_INVOICE_SECTION_FOOTER", @"You can optionally take a picture with your device of the receipt to include with your contract request.");
//            break;
		case ADDRESS_SECTION:
            title = NSLocalizedString(@"INSURANCE_ADDRESS_SECTION_FOOTER", @"Please use your billing address.");
            break;
		case BIRTH_DATE_SECTION:
            title = NSLocalizedString(@"INSURANCE_BIRTH_DATE_SECTION_FOOTER", @"Please enter your birthday so that it may be confirmed that you are of age to sign a contract.");
            break;
		case BANK_SECTION:
            title = NSLocalizedString(@"INSURANCE_BANK_SECTION_FOOTER", @"I allow European Warranty Partners SE to debit the amount to the account given here.");
            break;
		case ROBBERY_SECTION:
            title = NSLocalizedString(@"INSURANCE_ROBBERY_SECTION_FOOTER", @"Increases your rate.");
            break;
		case COST_SECTION:
            title = NSLocalizedString(@"INSURANCE_MONTHLY_SECTION_FOOTER", @"This is the amount you will be charged periodically.");
            break;
		case INFO_SECTION:
            //title = NSLocalizedString(@"INSURANCE_INFO_SECTION_FOOTER", @"Important Information");
            break;
		case ACCEPT_CONDITIONS_SECTION:
			title = NSLocalizedString(@"INSURANCE_ACCEPT_CONDITIONS_SECTION_FOOTER", @"By choosing YES you acknowledge that you have read the and accept the insurance conditions.");
            break;
        default:
            break;
    }
    return title;
}



- (void)generateTableData
{
	Insurance *insuranceData = [(InsuranceTabbarController *)[self tabBarController] insuranceData];
	
	self.tableArray = [NSArray arrayWithObjects:[insuranceData deviceString], 
					   [insuranceData addressString], 
					   [insuranceData birthDateString], 
					   [insuranceData bankConnectionString], 
					   NSLocalizedString(@"INSURANCE_ROBBERY_SWITCH_LABEL", @"Against Robbery"), 
					   [insuranceData monthlyRateString], 
					   [insuranceData importantInformationString], 
					   @"", 
					   nil];
	
	[concludeContractButton setEnabled:![insuranceData insured]];
	[concludeContractButton setTitle:NSLocalizedString(@"INSURANCE_CONCLUDED_BUTTON_TITLE", @"Contract Concluded") forState:UIControlStateDisabled];
	[concludeContractButton setTitle:NSLocalizedString(@"INSURANCE_CONCLUDE_BUTTON_TITLE", @"Conclude Contract") forState:UIControlStateNormal];



}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/


/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source.
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
    }   
}
*/


/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/


/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/



- (UISwitch *)switchCtl
{
    if (switchCtl == nil) 
    {
        CGRect frame = CGRectMake(190.0, 10.0, 94.0, 27.0);
        switchCtl = [[UISwitch alloc] initWithFrame:frame];
        [switchCtl addTarget:self action:@selector(switchAction:) forControlEvents:UIControlEventValueChanged];
        
        // in case the parent view draws with a custom color or gradient, use a transparent color
        switchCtl.backgroundColor = [UIColor clearColor];
    }
	
	Insurance *insuranceData = [(InsuranceTabbarController *)[self tabBarController] insuranceData];

	[switchCtl setOn:insuranceData.robbery animated:NO];
    return switchCtl;
}

- (void)switchAction:(id)sender
{
	Insurance *insuranceData = [(InsuranceTabbarController *)[self tabBarController] insuranceData];

	[insuranceData toggleRobbery];
	[self generateTableData];
	[self.tableView reloadData];
}

#pragma mark -
#pragma mark Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	Insurance *insuranceData = [(InsuranceTabbarController *)[self tabBarController] insuranceData];
	
	if (![insuranceData insured]) {
		if (indexPath.section == DEVICE_SECTION) {
			InsuranceDeviceDetailsViewController *insuranceDeviceDetailsViewController = [[InsuranceDeviceDetailsViewController alloc] initWithNibName:@"InsuranceDeviceDetailsViewController" bundle:nil];
			[insuranceDeviceDetailsViewController setInsuranceData:insuranceData];
			//[insuranceDeviceDetailsViewController setInsuranceViewController:self.insuranceViewController];
			[self.navigationController pushViewController:insuranceDeviceDetailsViewController animated:YES];
			[insuranceDeviceDetailsViewController release];
		} else if (indexPath.section == ADDRESS_SECTION) {
			InsuranceAddressViewController *insuranceAddressViewController = [[InsuranceAddressViewController alloc] initWithNibName:@"InsuranceAddressViewController" bundle:nil];
			[insuranceAddressViewController setInsuranceData:insuranceData];
			[insuranceAddressViewController setInsuranceViewController:self.insuranceViewController];
			[self.navigationController pushViewController:insuranceAddressViewController animated:YES];
			[insuranceAddressViewController release];
		} else if (indexPath.section == BANK_SECTION) {
			InsuranceBankViewController *insuranceBankViewController = [[InsuranceBankViewController alloc] initWithNibName:@"InsuranceBankViewController" bundle:nil];
			[insuranceBankViewController setInsuranceData:insuranceData];
			[insuranceBankViewController setInsuranceViewController:self.insuranceViewController];
			[self.navigationController pushViewController:insuranceBankViewController animated:YES];
			[insuranceBankViewController release];
		} else if (indexPath.section == BIRTH_DATE_SECTION) {
			BirthdayViewController * birthdayViewController = [[BirthdayViewController alloc] initWithNibName:@"BirthdayViewController" bundle:nil];
			[birthdayViewController setInsuranceData:insuranceData];
			[self.navigationController pushViewController:birthdayViewController animated:YES];
			[birthdayViewController release];
		}
	} else {
		[tableView deselectRowAtIndexPath:indexPath animated:NO];
	}

}


- (IBAction)concludeContract:(id)sender
{
	Insurance *insuranceData = [(InsuranceTabbarController *)[self tabBarController] insuranceData];
	
	if ([insuranceData insured]) {
		// device is insured, so do nothing
	} else {
		// device is not insured, so do the checks
		if ([self.segmentedControl selectedSegmentIndex] == 0) {
			[insuranceData conditionsHaveBeenAccepted];
		} else {
			[insuranceData conditionsHaveBeenRejected];
			
		}
		
		if ([insuranceData noDataMissing]) {
			// transfer the data
			[insuranceData sendInsuranceDataWithinView:self.view];
		}
		
	}

}

#pragma mark -
#pragma mark Notifications
- (void) dateChanged:(NSNotification *) aNotification
{
	[self generateTableData];
	[self.tableView reloadData];
}


#pragma mark -
#pragma mark Memory management

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Relinquish ownership any cached data, images, etc. that aren't in use.
}

- (void)viewDidUnload {
    // Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
    // For example: self.myOutlet = nil;
}


- (void)dealloc {
    [super dealloc];
}


@end

